package com.linskating.wheat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linskating.wheat.annotations.aop.LogOperation;
import com.linskating.wheat.common.BaseResponse;
import com.linskating.wheat.common.ErrorCode;
import com.linskating.wheat.common.PageRequest;
import com.linskating.wheat.common.ResultUtils;
import com.linskating.wheat.constant.UserConstant;
import com.linskating.wheat.exception.BusinessException;
import com.linskating.wheat.model.domain.User;
import com.linskating.wheat.model.request.userRequest.*;
import com.linskating.wheat.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:5173", methods = {RequestMethod.GET, RequestMethod.POST}, allowCredentials = "true")
@LogOperation
public class UserController implements UserConstant {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String wheatCode = userService.getUniqueUID();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, wheatCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户或密码错误");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        userService.currentUser(request);
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> currentUser(HttpServletRequest request) {
        User user = userService.currentUser(request);
        return ResultUtils.success(user);
    }

    @PostMapping("/search")
    public BaseResponse<List<User>> searchUsers(@RequestBody UserSearchRequest userSearchRequest, HttpServletRequest request) {
        userService.currentUser(request);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String curUserName = userService.currentUser(request).getUsername();
        String username = userSearchRequest.getUserName();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream()
                .filter(user -> !curUserName.equals(user.getUsername()))
                .map(user -> userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody UserDeleteRequest userDeleteRequest, HttpServletRequest request) {
        if (userService.isNotAdmit(request)) {
            throw new BusinessException(ErrorCode.NOT_AUTH);
        }
        long id = userDeleteRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    @PostMapping("/search/allTags")
    public BaseResponse<List<User>> searchUsersByAllTagsBySQL(@RequestBody UserSearchByTagsRequest tagsRequest, HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagsRequest.getTagsList())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User currentUser = userService.currentUser(request);
        List<User> userList = userService.searchUsersByAllTagsByMemory(tagsRequest.getTagsList(), currentUser.getId());
        return ResultUtils.success(userList);
    }

    @PostMapping("/search/someTags")
    public BaseResponse<List<User>> searchUsersBySomeTagsBySQL(@RequestBody UserSearchByTagsRequest tagsRequest, HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagsRequest.getTagsList())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User currentUser = userService.currentUser(request);
        List<User> userList = userService.searchUsersBySomeTagsBySQL(tagsRequest.getTagsList(), currentUser.getId());
        return ResultUtils.success(userList);
    }

    @PostMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(@RequestBody PageRequest pageRequest, HttpServletRequest request) {
        User user = userService.currentUser(request);
        Page<User> userPage = userService.recommendUsers(pageRequest.getThePageNum(), pageRequest.getPageSize(), user.getId());
        return ResultUtils.success(userPage);
    }

    @GetMapping("/totalUserCount")
    public BaseResponse<Long> totalUserCount(HttpServletRequest request) {
        userService.currentUser(request);
        return ResultUtils.success(userService.count(new QueryWrapper<>()) - 1);
    }

    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(int count, HttpServletRequest request) {
        if (count <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.currentUser(request);
        List<User> matchUserList = userService.matchUser(count, currentUser);
        return ResultUtils.success(matchUserList);
    }

    @PostMapping("/updateUser")
    public BaseResponse<Integer> updateUserInfo(@RequestBody User toUpdateUser, HttpServletRequest request) {
        if (toUpdateUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 鉴权操作，判断是否是管理员或者是否是自己
        User currentUser = userService.currentUser(request);
        if (currentUser.getUserRole() != ADMIN_ROLE && !toUpdateUser.getId().equals(currentUser.getId())) {
            throw new BusinessException(ErrorCode.NOT_AUTH);
        }
        int updateUserCount = userService.updateUserInfo(toUpdateUser);
        if (updateUserCount <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(updateUserCount);
    }

    @PostMapping("/updateAvatarUrl")
    public BaseResponse<String> updateAvatarUrl(@RequestParam("file") MultipartFile file, @RequestParam("id") Long userId, HttpServletRequest request) {
        // 鉴权操作，判断是否是管理员或者是否是自己
        User currentUser = userService.currentUser(request);
        if (currentUser.getUserRole() != ADMIN_ROLE && !currentUser.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.NOT_AUTH);
        }
        String fileUrl = userService.updateAvatarUrl(file, userId);
        return ResultUtils.success(fileUrl);
    }
}
